﻿using System;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using D3D10Scene;

namespace D3DImageTest
{
    public partial class Window1 : Window
    {
        private D3DImageEx m_d3DImageEx;
        private D3D10TestScene m_d3D10Scene;

        public Window1()
        {
            InitializeComponent();
            Loaded += Window1_Loaded;
        }

        void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            /* Create a new D3DImageEx class */
            m_d3DImageEx = new D3DImageEx();
            
            /* Set our image's source to our D3DImage9Ex */
            d3dScene.Source = m_d3DImageEx;

            /* Create a new D3DTest scene */
            m_d3D10Scene = new D3D10TestScene();

            /* Set the backbuffer, which is a ID3D10Texture2D pointer */
            m_d3DImageEx.SetBackBufferEx(D3DResourceTypeEx.ID3D10Texture2D, m_d3D10Scene.GetRenderTarget());

            CompositionTarget.Rendering += CompositionTarget_Rendering;
        }

        /// <summary>
        /// Invalidates entire D3DImage area
        /// </summary>
        private void InvalidateD3DImage()
        {
            m_d3DImageEx.Lock();
            m_d3DImageEx.AddDirtyRect(new Int32Rect()
            {
                X = 0,
                Y = 0,
                Height = m_d3DImageEx.PixelHeight,
                Width = m_d3DImageEx.PixelWidth
            });
            m_d3DImageEx.Unlock();
        }

        private void CompositionTarget_Rendering(object sender, EventArgs e)
        {
            /* Render D3D10 test scene */
            m_d3D10Scene.Render();

            /* Invalidate our D3DImage */
            InvalidateD3DImage();
        }
    }
}
